import notification from 'ant-design-vue/es/notification'
import fs from 'file-saver'
import * as XLSX from 'xlsx/xlsx.mjs'

export function xlsx(json, fields,wscols, filename = '.xlsx') {
    json.forEach(item => {
        for (let i in item) {
            if (fields.hasOwnProperty(i)) {
                item[fields[i]] = item[i];
            }
            delete item[i]; 
        }
    })
    let sheetName = filename
    let wb = XLSX.utils.book_new()  
    let ws = XLSX.utils.json_to_sheet(json, { header: Object.values(fields) }) 
    ws["!cols"] = wscols;
    wb.SheetNames.push(sheetName)
    wb.Sheets[sheetName] = ws
    const defaultCellStyle = { font: { name: "Verdana", sz: 13, color: "FF00FF88" }, alignment:{horizontal:'center',vertcal:'center',indent:0},fill: { fgColor: { rgb: "FFFFAA00" } } };
    let wopts = { bookType: 'xlsx', bookSST: false, type: 'binary', cellStyles: true, defaultCellStyle: defaultCellStyle, showGridLines: false }  
    let wbout = XLSX.write(wb, wopts)
    let blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' })
    fs.saveAs(blob, filename + '.xlsx')
}

const s2ab = s => {
    var buf;
    if (typeof ArrayBuffer !== 'undefined') {
        buf = new ArrayBuffer(s.length)
        var view = new Uint8Array(buf)
        for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff
        return buf
    } else {
        buf = new Array(s.length);
        for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
        return buf;
    }
}


export function timeFix() {
  const time = new Date()
  const hour = time.getHours()
  return hour < 9 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 20 ? '下午好' : '晚上好'
}

export function welcome () {
  const arr = ['休息一会儿吧', '准备吃什么呢?', '要不要打一把 DOTA', '我猜你可能累了']
  const index = Math.floor(Math.random() * arr.length)
  return arr[index]
}

export function generateMixed(n) {
  var res = "";
  var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    for(var i = 0; i < n ; i ++) {
        var id = Math.ceil(Math.random()*35);
        res += chars[id];
    }
    return res;
}

export function triggerWindowResizeEvent () {
  const event = document.createEvent('HTMLEvents')
  event.initEvent('resize', true, true)
  event.eventType = 'message'
  window.dispatchEvent(event)
}

export function handleScrollHeader (callback) {
  let timer = 0

  let beforeScrollTop = window.pageYOffset
  callback = callback || function () {}
  window.addEventListener(
    'scroll',
    event => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        let direction = 'up'
        const afterScrollTop = window.pageYOffset
        const delta = afterScrollTop - beforeScrollTop
        if (delta === 0) {
          return false
        }
        direction = delta > 0 ? 'down' : 'up'
        callback(direction)
        beforeScrollTop = afterScrollTop
      }, 50)
    },
    false
  )
}

export function isIE () {
  const bw = window.navigator.userAgent
  const compare = (s) => bw.indexOf(s) >= 0
  const ie11 = (() => 'ActiveXObject' in window)()
  return compare('MSIE') || ie11
}

export function removeLoadingAnimate (id = '', timeout = 1500) {
  if (id === '') {
    return
  }
  setTimeout(() => {
    document.body.removeChild(document.getElementById(id))
  }, timeout)
}

export function checkAmount(val) {
    if (!(/^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/.test(val))) {
        return false;
    }
    return true;
}

export function checkBankno(bankno) {
  var lastNum = bankno.substr(bankno.length - 1, 1); //取出最后一位（与luhm进行比较）
  var first15Num = bankno.substr(0, bankno.length - 1); //前15或18位
  var newArr = [];

  for (var i = first15Num.length - 1; i > -1; i--) { //前15或18位倒序存进数组
    newArr.push(first15Num.substr(i, 1));
  }

  var arrJiShu = []; //奇数位*2的积 <9
  var arrJiShu2 = []; //奇数位*2的积 >9
  var arrOuShu = []; //偶数位数组
  for (var j = 0; j < newArr.length; j++) {
    if ((j + 1) % 2 == 1) { //奇数位
      if (parseInt(newArr[j]) * 2 < 9)
        arrJiShu.push(parseInt(newArr[j]) * 2);
      else
        arrJiShu2.push(parseInt(newArr[j]) * 2);
    } else //偶数位
      arrOuShu.push(newArr[j]);
  }

  var jishu_child1 = []; //奇数位*2 >9 的分割之后的数组个位数
  var jishu_child2 = []; //奇数位*2 >9 的分割之后的数组十位数
  for (var h = 0; h < arrJiShu2.length; h++) {
    jishu_child1.push(parseInt(arrJiShu2[h]) % 10);
    jishu_child2.push(parseInt(arrJiShu2[h]) / 10);
  }

  var sumJiShu = 0; //奇数位*2 < 9 的数组之和
  var sumOuShu = 0; //偶数位数组之和
  var sumJiShuChild1 = 0; //奇数位*2 >9 的分割之后的数组个位数之和
  var sumJiShuChild2 = 0; //奇数位*2 >9 的分割之后的数组十位数之和
  var sumTotal = 0;
  for (var m = 0; m < arrJiShu.length; m++) {
    sumJiShu = sumJiShu + parseInt(arrJiShu[m]);
  }
  for (var n = 0; n < arrOuShu.length; n++) {
    sumOuShu = sumOuShu + parseInt(arrOuShu[n]);
  }
  for (var p = 0; p < jishu_child1.length; p++) {
    sumJiShuChild1 = sumJiShuChild1 + parseInt(jishu_child1[p]);
    sumJiShuChild2 = sumJiShuChild2 + parseInt(jishu_child2[p]);
  }
  sumTotal = parseInt(sumJiShu) + parseInt(sumOuShu) + parseInt(sumJiShuChild1) + parseInt(sumJiShuChild2);
  var k = parseInt(sumTotal) % 10 == 0 ? 10 : parseInt(sumTotal) % 10;
  var luhm = 10 - k;
  if (lastNum == luhm) {
    return true;
  } else {
    return false;
  }
}


export function checkIDCard(idcode){
  var weight_factor = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2];
  var check_code = ['1', '0', 'X' , '9', '8', '7', '6', '5', '4', '3', '2'];
  var code = idcode + "";
  var last = idcode[17];//最后一个
  var seventeen = code.substring(0,17);
  // ISO 7064:1983.MOD 11-2
  // 判断最后一位校验码是否正确
  var arr = seventeen.split("");
  var len = arr.length;
  var num = 0;
  for(var i = 0; i < len; i++){
      num = num + arr[i] * weight_factor[i];
  }
  var resisue = num%11;
  var last_no = check_code[resisue];
  var idcard_patter = /^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/;
 
  var format = idcard_patter.test(idcode);
 
  return last === last_no && format ? true : false;
}

export function CheckSocialCreditCode(Code) { 
	var patrn = /^[0-9A-Z]+$/;  
	if ((Code.length != 18) || (patrn.test(Code) == false)) {  
		return false;  
	} else {  
		var Ancode;
		var Ancodevalue;   
		var total = 0;  
		var weightedfactors = [1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28];
		var str = '0123456789ABCDEFGHJKLMNPQRTUWXY';  
		for (var i = 0; i < Code.length - 1; i++) {  
			Ancode = Code.substring(i, i + 1);  
			Ancodevalue = str.indexOf(Ancode);  
			total = total + Ancodevalue * weightedfactors[i];  
	    }  
		var logiccheckcode = 31 - total % 31;  
		if (logiccheckcode == 31) {  
			logiccheckcode = 0;  
        }  
		var Str = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,T,U,W,X,Y";  
		var Array_Str = Str.split(',');  
		logiccheckcode = Array_Str[logiccheckcode]; 
		var checkcode = Code.substring(17, 18);  
		if (logiccheckcode != checkcode) {  
			return false;  
		}
		return true;  
	}  
}


export function checkPhone(val) {
  if (!(/^1(3[0-9]|4[0-9]|5[0-9]|6[0-9]|7[0-9]|8[0-9]|9[0-9])\d{8}$/.test(val))) {
    return false;
  }
  return true;
}


export function checkPhoneOrLandline(val) {
    if (!/^(((\d{3,4}-)?[0-9]{7,8})|(1(3|4|5|6|7|8|9)\d{9}))$/.test(val)) {
        return false;
    }
    return true;
}


export function checkNumber(val) {
    if (!/^[0-9,]*$/.test(val)) {
        return false;
    }
    return true;
}

export function checkChinese(val) {
    var pattern = new RegExp("[\u4E00-\u9FA5]+");
    if(!pattern.test(val)){
        return false;
    }
    return true;
}


export function checkEnglish(val) {
    var pattern = new RegExp("[A-Za-z]+");
    if(!pattern.test(val)){
        return false;
    }
    return true;
}
 

export function arrUnique(arr, key) {
  let returnArr = [];
  if (key) {
      const obj = {};
      returnArr = arr.reduce((cur, next) => {
          obj[next[key]] ? '' : obj[next[key]] = true && cur.push(next);
          return cur;
      }, []);
      return returnArr;
  }
  const obj = {};
  returnArr = arr.reduce((cur, next) => {
      !cur.includes(next) && cur.push(next);
      return cur;
  }, []);
  return returnArr;
}


export function previewFile(files) {
    if (!files) {
        notification.error({
        message: '温馨提示',
        description: '暂无文件'
      })
        return;
    }
  var form = document.createElement('form');
  form.action = files;
  form.target = '_blank';
  form.method = 'get';
  document.body.appendChild(form);
  form.submit();
}
// a 标签预览
export function previewAFile(files) {
  if (!files) {
      notification.error({
      message: '温馨提示',
      description: '暂无文件'
    })
      return;
  }
  var a = document.createElement('a');
  a.style.display = 'none';
  a.target = '_blank';
  a.href = files;
  a.click();
  URL.revokeObjectURL(a.href);
}

export function checkNum(c1,c2){
if(!isfloat(c1)||c1==""||c1==null){
c1=0;
}
if(!isfloat(c2)||c2==""||c2==null){
c2=0; 
}

var c=0;
c=c.add(c1).add(c2);
return c;
}
function isfloat(oNum){
    if(!oNum) return false;
    var strP=/^\d+(\.\d+)?$/;
    if(!strP.test(oNum)) return false;
    try{
        if(parseFloat(oNum)!=oNum) return false;
    }catch(ex){
        return false;
    }
    return true;
}

function accAdd(arg1,arg2){  
    var r1,r2,m;
    try{r1=arg1.toString().split(".")[1].length}
    catch(e){r1=0}    
    try{r2=arg2.toString().split(".")[1].length}
    catch(e){r2=0}   
    m=Math.pow(10,Math.max(r1,r2))    
    return (arg1 * m + arg2 * m) / m
}
//给Number类型增加一个add方法，调用起来更加方便。
Number.prototype.add = function (arg){    
    return accAdd(arg,this);
}
/* ------------新增方法------------- */

// 判断数组中对象值是否重复存在
export function checkRepeat(array, key) {
  if (array.length > 0) {
    return !array.some(function (item, index) {
      return item[key] !== array[0][key];
    });
  } else {
    return true;
  }
}
